import java.util.Arrays;

public class TestHeap {
    public int[] elem;
    public int usedSize;

    public TestHeap(){
        this.elem = new int[10];
    }

    public void initElem(int[] array){
        for (int i = 0; i < array.length; i++) {
            this.elem[i] = array[i];
            usedSize++;
        }
    }

    public void createHeap(){
        for (int parent = (usedSize-1-1) / 2; parent >= 0; parent--) {
            siftDown(parent,usedSize);
        }
    }

    private void siftDown(int parent, int usedSize) {
        int child = 2*parent + 1;
        while(child < usedSize){
            if(child + 1 < usedSize && elem[child] < elem[child + 1]){
                child++;
            }
            if(elem[child] > elem[parent]){
                swap(elem,parent,child);
                parent = child;
                child = 2*parent + 1;
            }else{
                break;
            }
        }
    }

    public void swap(int[] array,int i,int j){
        int tmp = array[i];
        array[i] = array[j];
        array[j] = tmp;
    }

    public void offer(int val){
        if(isFull()){
            elem = Arrays.copyOf(elem,elem.length*2);
        }
        elem[usedSize] = val;
        siftUp(usedSize);
        usedSize++;
    }

    private void siftUp(int child) {
        int parent = (child - 1)/2;
        while(parent >= 0){
            if(elem[child] > elem[parent]){
                swap(elem,parent,child);
                child = parent;
                parent = (child - 1)/2;
            }else{
                break;
            }
        }
    }

    public void poll(){
        if(isEmpty()) return;
        swap(elem,0,usedSize - 1);
        usedSize--;
        siftDown((usedSize-1-1) / 2,usedSize);
    }

    public void Del(int val){
        if(isEmpty()){
            return;
        }
        int i = 0;
        for (; i < usedSize; i++) {
            if(elem[i] == val) {
                break;
            }
        }
        if(i == usedSize - 1){
            System.out.println("没有找到该数");
            return;
        }
        swap(elem,i,usedSize - 1);
        siftDown((usedSize-1-1) / 2,usedSize);
        usedSize--;
    }

    public boolean isFull(){
        return usedSize == elem.length;
    }

    public boolean isEmpty(){
        return usedSize == 0;
    }

    public void heapSort(){
        int end = usedSize - 1;
        while(end > 0){
            swap(elem,0,end);
            siftDown(0,end);
            end--;
        }
    }
}
